<?php
/**
 * @author spenceryg
 * @date 2022/4/14
 * @time 4:45 下午
 * @focus love & life
 */


namespace app\common\lib\verify;


use app\common\lib\verify\interfaces\Verify;
use PHPMailer\PHPMailer\PHPMailer;

class EmailVerify implements Verify
{

    protected $mail = null;
    protected $template = null;

    public function sendCode(string $to, $code)
    {
        $this->mail->isHTML(true);                                  //Set email format to HTML
        $this->mail->Subject = config('email.template.' . $this->template . '.topic');
        $this->mail->Body    = str_replace('{code}', $code, config('email.template.' . $this->template . '.content'));
        try{
            $this->mail->setFrom( config('email.username'),  config('email.from_name'));
            $this->mail->addAddress($to);
            $this->mail->send();
        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }

    public function __construct(string $template = 'default')
    {
        $mail =  new PHPMailer(true);

        $mail->isSMTP();                                            //Send using SMTP
        $mail->Host       = config('email.host');                     //Set the SMTP server to send through
        $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
        $mail->Username   = config('email.username');                     //SMTP username
        $mail->Password   = config('email.password');                               //SMTP password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
        $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

        $this->template = $template;
        $this->mail = $mail;
    }
}
